/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */

/**
 * 计算数组中每列数据的平均值和标准差
 *
 * @param {Tensor2d} data 用于独立计算每列数据的平均值的标准差的数据集
 * @returns {Object} 包含每列数据的平均值和标准差的一维张量
 */
export function determineMeanAndStddev(data) {
  const dataMean = data.mean(0);
  // TODO(bileschi): Simplify when and if tf.var / tf.std added to the API.
  const diffFromMean = data.sub(dataMean);
  const squaredDiffFromMean = diffFromMean.square();
  const variance = squaredDiffFromMean.mean(0);
  const dataStd = variance.sqrt();
  return { dataMean, dataStd };
}

/**
 * 输入给定的平均值和标准差。通过减去平均值并除以标准差，实现数据集标准化
 *
 * @param {Tensor2d} data: 待标准化的数据，形状为 [numSamples, numFeatures]
 * @param {Tensor1d} dataMean: 输入的数据平均值，形状为 [numFeatures].
 * @param {Tensor1d} dataStd: 输入的数据标准差，形状为 [numFeatures]
 * @returns {Tensor2d}: 返回的张量和输入的数据形状相同，但通过标准化，每列数据的平均值变为0，标准差变为单位标准差
 */
export function normalizeTensor(data, dataMean, dataStd) {
  return data.sub(dataMean).div(dataStd);
}
